package com.maxbill.core.filter;

import ch.qos.logback.classic.spi.ILoggingEvent;
import ch.qos.logback.classic.spi.IThrowableProxy;
import ch.qos.logback.core.filter.Filter;
import ch.qos.logback.core.spi.FilterReply;
import com.maxbill.base.bean.Message;
import com.maxbill.util.DateUtil;
import lombok.extern.log4j.Log4j2;
import org.springframework.stereotype.Component;

import static com.maxbill.fxui.body.LogsWindow.showLog;

/**
 * 日志过滤器
 *
 * @author MaxBill
 * @date 2019/07/19
 */
@Log4j2
@Component
public class LogFilter extends Filter<ILoggingEvent> {

    @Override
    public FilterReply decide(ILoggingEvent event) {
        String exception = "";
        IThrowableProxy throwableProxy = event.getThrowableProxy();
        if (throwableProxy != null) {
            exception = exception.concat(throwableProxy.getClassName());
            exception = exception.concat(" ").concat(throwableProxy.getMessage());
            for (int i = 0; i < throwableProxy.getStackTraceElementProxyArray().length; i++) {
                exception = exception.concat(throwableProxy.getStackTraceElementProxyArray()[i].toString());
            }
        }
        Message message = new Message();
        message.setTime(DateUtil.timeStampToDateTime(event.getTimeStamp()));
        message.setType(event.getLevel().levelStr);
        message.setBody(event.getFormattedMessage());
        message.setClassName(event.getLoggerName());
        message.setException(exception);
        showLog(message);
        return FilterReply.ACCEPT;
    }

}
